//
//  SearchViewController.m
//  CPU_Utility
//
//  Created by leonardo on 15/10/12.
//  Copyright © 2015年 leonardo. All rights reserved.
//

#import "SearchViewController.h"
#import <AFNetworking.h>
#import <MJRefresh.h>
#import "Util.h"
#import "SearchTermsModel.h"
#import "SearchResultModel.h"
#import "SearchResultTableViewCell.h"
#import <MJExtension.h>
//#import <MMProgressHUD.h>
#import <KVNProgress.h>
#import "CompareViewController.h"
#import "CPUDetailModel.h"
#import <JMHoledView.h>
@interface SearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>{
    UISearchBar * _searchBar;//搜索栏
    UITableView * _tableView;//表格
    NSMutableArray * _arrData;//
   
    //NSMutableDictionary * _dictSearchTerms;
    SearchResultModel * searchResultModel;//搜索数据结果模型
    
    //JMHoledView * _holdView;
    
}

@end

@implementation SearchViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        _isFromSelectOldCPU = NO;
        _compareViewController = [CompareViewController new ];
        
           NSMutableDictionary * dictSearchTerms = [NSMutableDictionary dictionaryWithDictionary: @{@"c":@"Advanced_List_V1",
                                 //@"manuId":@"125-55",
                                 @"noParam":@"1",
                                 @"num":@20,
                                 @"orderBy":@"14",
                                 @"page":@1,
                                 @"paramVal":@"",
                                 @"priceId":@"noPrice",
                                 @"keyword":@"",
                                 @"subcateId":@"28"//@"383" 服务器代号
        
                                 }];
            
            _searchTerms = [SearchTermsModel objectWithKeyValues:dictSearchTerms];

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self initial];
    [self loadData];
    [self createUI];
    //设置小白模式引导页
    
}
/**
 *  初始化
 */
-(void)initial{
    //self.navigationController.navigationBar.hidden = YES;
    _arrData = [NSMutableArray array];
//    c	Advanced_List_V1
//    manuId	125-55   ，125 intel ，55 amd
//    noParam	 1 ？
//    num	20 每页个数
//    orderBy	 14 排序：1:热门，14:最新 ，4，价高，3:价低
//    page	1 页码
//    paramVal	s1584-s6219-s6221
//    priceId	 300 价格挡：noPrice ，0：0-300，300：300-500，500:500－1000，1000，2000
//    subcateId	28		子类
    
    
//   NSMutableDictionary * dictSearchTerms = [NSMutableDictionary dictionaryWithDictionary: @{@"c":@"Advanced_List_V1",
//                         //@"manuId":@"125-55",
//                         @"noParam":@"1",
//                         @"num":@20,
//                         @"orderBy":@"14",
//                         @"page":@1,
//                         @"paramVal":@"",
//                         @"priceId":@"noPrice",
//                         @"keyword":@"",
//                         @"subcateId":@"28"//@"383" 服务器代号
//                                                                                            
//                         }];
//    
//    _searchTerms = [SearchTermsModel objectWithKeyValues:dictSearchTerms];
   // searchResultModel = [[SearchResultModel alloc]init];
    
}
/**
 *  加载数据
 */
-(void)loadData{
    //如果是第一次搜索  ,搜索结果model 为空
    if (!searchResultModel){
        //[MMProgressHUD showWithStatus:@"玩命加载中..."];
        [KVNProgress showWithStatus:@"加载中..."];
    }
    
    NSString * url = @"http://lib3.wap.zol.com.cn/index.php?";
    
    NSMutableDictionary * dictPara = _searchTerms.keyValues;
    
    AFHTTPRequestOperationManager * manager = [Util getAFNetworkingManager];
    [manager GET:url parameters:dictPara success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        //如果 搜索结果model 为空
        if (!searchResultModel) {
            searchResultModel = [SearchResultModel objectWithKeyValues:responseObject];
            
        }
        else{// 否则搜索结果model 追加数据
            [searchResultModel.data addObjectsFromArray: [SearchResultModelData objectArrayWithKeyValuesArray:responseObject[@"data"]]];
        }
      
        
        [_tableView reloadData];
        //如果是最后一页,
        if ([_searchTerms.page intValue] * [_searchTerms.num intValue] >= [searchResultModel.allNum intValue]) {
            [_tableView.footer endRefreshingWithNoMoreData]; //上拉栏提示没有更多数据
           
        }else{
            [_tableView.footer endRefreshing];
        }
        //下拉栏 结束刷新
        [_tableView.header endRefreshing];
        //如果搜索结果 没有
        if (searchResultModel.data.count == 0) {
          // [MM]
            [KVNProgress showErrorWithStatus:@"查找不到数据...\n 请换关键字"];
        }
        else{
            //[MMProgressHUD dismissWithSuccess:@"加载完成" ];
            [KVNProgress dismiss];
            if (_isFromSelectOldCPU || _isFromSelectNewCPU) {
                [self showHUDSelectCPU];
            }
           
        }

        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [_tableView.header endRefreshing];
        if (searchResultModel != nil) { // 刷 newpage 失败
            [_tableView.footer setState:MJRefreshStateError];
           // MJRefreshAutoNormalFooter * footer = [MJRefreshAutoNormalFooter new];
//            [footer setTitle:@"网络错误,上拉重试" forState:MJRefreshStateIdle];
//            [footer setRefreshingTarget:self refreshingAction:@selector(pullUp:)];
//            _tableView.footer = footer;
       }
        else{//新 搜索关键字 失败
            [_tableView.footer setHidden:YES];
            [KVNProgress showErrorWithStatus:@"网络超时\n请重试!"];
        }
        
       // [_tableView reloadData];
        //[KVNProgress showErrorWithStatus:@"加载失败!\n请重试"];
    }];
    
   // manager.re
}
/**
 *  创建UI
 */
-(void)createUI{
    //搜索栏
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0, 0, 0)];
    _searchBar.delegate = self;
    
    _searchBar.barStyle = UIBarStyleDefault;
    //_searchBar.backgroundColor = [UIColor blackColor];
    _searchBar.showsCancelButton = YES;
   // _searchBar.showsSearchResultsButton = YES;
    _searchBar.placeholder = @"请输入CPU关键字";
    self.navigationItem.titleView = _searchBar;
    
    //tabbar设置
    [self.navigationController.navigationBar setTranslucent:NO];
    [self.tabBarController.tabBar setTranslucent:NO];
    //tableview
    
   
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR_HEIGHT - NAVI_HEIGHT - ((_isFromSelectOldCPU || _isFromSelectNewCPU)? 0 : TABBAR_HEIGHT) ) style:UITableViewStylePlain];
    
//    _tableView = [[UITableView alloc]initWithFrame:CGRectInset(self.view.frame, 2, 2) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 90.0f;
    [self.view addSubview:_tableView];

    //设置 下拉 刷新
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       // if([_tableView.footer class] != [MJRefreshAutoNormalFooter class] ){
        _tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(pullUp:)];
       // }
        
        [self searchBarSearchButtonClicked:_searchBar];
        
        //NSLog(@"refresh");
    }];
    //设置 上拉 刷新 新page页面
    _tableView.footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(pullUp:)];


    
    
    
}
/**
 *  上拉回调事件
 *
 *  @param sender MJRefreshAutoGifFooter
 */
-(void)pullUp:(MJRefreshAutoGifFooter*) sender{
    int page = [_searchTerms.page intValue];
    _searchTerms.page =[NSString stringWithFormat:@"%i",(page + 1)];
    [self loadData];
}

/**
 *  点击搜索
 *
 *  @param searchBar 搜索栏
 */
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString * keyword =  searchBar.text;
    //设置上拉栏控件 为默认的
    MJRefreshBackNormalFooter * footer = [MJRefreshBackNormalFooter new];
    [footer setRefreshingTarget:self refreshingAction:@selector(pullUp:)];
    _tableView.footer = footer;
    
    _searchTerms.keyword= keyword;
    _searchTerms.page = @"1";
    searchResultModel = nil;
    
    [self loadData];
    [_searchBar resignFirstResponder];
}
//搜索栏 点击取消
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    _searchBar.text = @"";
    [_searchBar resignFirstResponder];
}


//返回行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  searchResultModel.data.count;
    
}
//定制cell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellId = @"cell";
    SearchResultTableViewCell * cell = [_tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SearchResultTableViewCell" owner:self options:nil]lastObject];
    }
    SearchResultModelData * model  = searchResultModel.data[indexPath.row];
    [cell configWithModel:model];
    return  cell;
}
//点击单元格
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //
    _compareViewController = [_compareViewController init];
    CPUDetailModel * model = [CPUDetailModel new];
    model.name = [searchResultModel.data[indexPath.row] name];
    model.productId = [searchResultModel.data[indexPath.row] id];
    model.smallImage = [searchResultModel.data[indexPath.row] smallPic];
    if (_isFromSelectOldCPU ) {
        _compareViewController.isFormSelectOldCPU = YES;
        _compareViewController.isFormSelectNewCPU = NO;
        _compareViewController.isFromSearchChontroller = NO;

    }
    else if(_isFromSelectNewCPU){
        _compareViewController.isFormSelectOldCPU = NO;
        _compareViewController.isFormSelectNewCPU = YES;
        _compareViewController.isFromSearchChontroller = NO;
    }
    else{
        _compareViewController.isFormSelectOldCPU = NO;
        _compareViewController.isFormSelectNewCPU = NO;
        _compareViewController.isFromSearchChontroller = YES;
    }
    
    [_compareViewController.ArrCpus addObject:model];
    //[self performSelectorInBackground:@selector(showHud) withObject:nil];
    
    [self.navigationController pushViewController:_compareViewController animated:YES];
    
}
-(void)showHud{
    [KVNProgress show];
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [_searchBar resignFirstResponder];
    if (_isFromSelectNewCPU ||_isFromSelectOldCPU) {
        _isFromSelectOldCPU = NO;
        _isFromSelectNewCPU = NO;
    }
}

- (void)showHUDSelectCPU{
    KVNProgressConfiguration *configuration = [[KVNProgressConfiguration alloc] init];
    //
    //        configuration.statusColor = [UIColor whiteColor];
    //        configuration.statusFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:15.0f];
    //        configuration.circleStrokeForegroundColor = [UIColor whiteColor];
    //        configuration.circleStrokeBackgroundColor = [UIColor colorWithWhite:1.0f alpha:0.3f];
    //        configuration.circleFillBackgroundColor = [UIColor colorWithWhite:1.0f alpha:0.1f];
    //        configuration.backgroundFillColor = [UIColor colorWithRed:0.173f green:0.263f blue:0.856f alpha:0.9f];
    //        configuration.backgroundTintColor = [UIColor colorWithRed:0.173f green:0.263f blue:0.856f alpha:1.0f];
    //        configuration.successColor = [UIColor whiteColor];
    //        configuration.errorColor = [UIColor whiteColor];
    
    configuration.circleSize = 0;
    configuration.lineWidth = 2.0f;
    configuration.fullScreen = YES;
    
    configuration.tapBlock = ^(KVNProgress *progressView) {
        [KVNProgress dismiss];
        [KVNProgress setConfiguration:[KVNProgressConfiguration new]];
        
    };
    
    // You can allow user interaction for behind views but you will losse the tapBlock functionnality just above
    // Does not work with fullscreen mode
    // Default is NO
    configuration.allowUserInteraction = YES;
    [KVNProgress setConfiguration:configuration];
    
    
    if (_isFromSelectOldCPU) {
        
       
        
        
        [KVNProgress showErrorWithStatus:@"在此搜索选择原CPU!" ];
       
        
        
    }
    else if(_isFromSelectNewCPU){
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"在此选择想要升级的CPU!" completion:^{
            [KVNProgress setConfiguration:[KVNProgressConfiguration new]];
        }];
        
    }

}






//-----------------------------------------------------------------------------------------------------
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
